extends Node
const Npc_definition = preload("res://src/npc_definition.gd")

var definitions = []

func _init():
	randomize()
	load_all_npcs()
	
func load_all_npcs():
	var dir = Directory.new()
	if dir.open("res://data/npc/") != OK:
		printerr("FAILED TO OPEN NPCS")
		return
	dir.list_dir_begin()
	var file_name = dir.get_next()
	while file_name != "":
		if dir.current_is_dir():
			load_npc_dir(file_name)
		else:
			print("Found file: " + file_name)
		file_name = dir.get_next()

func load_npc_dir(dir_name):
	var dir = Directory.new()
	if dir.open("res://data/npc/" + dir_name) != OK:
		printerr("FAILED TO OPEN NPC " + dir_name)
		return
	dir.list_dir_begin()
	var file_name = dir.get_next()
	while file_name != "":
		if dir.current_is_dir():
			pass
		else:
			if file_name.ends_with(".tres"):
				var resource : Npc_definition = load("res://data/npc/" + dir_name + "/" + file_name)
				var prefix = "res://data/npc/" + dir_name + "/" + file_name.substr(0,file_name.length()-5)
				register_npc(prefix, resource)
		file_name = dir.get_next()

func register_npc(prefix, resource):
	resource.prefix = prefix
	definitions.append(resource)

func generate_npc(window_items, achievements):
#	definitions.shuffle()
	var index = randi() % definitions.size()
	var def = definitions[index]
	var def_and_reason = def.random_spawn(window_items, achievements)
	if def_and_reason and def_and_reason.size() > 0:
		return def_and_reason
	return null
